import useLog from '@framework/useLog'
import type { App, Component } from 'vue'
import type * as VueRouter from 'vue-router'

/**
 * 自动导入当前项目内`components/Global`文件夹下面的所有组件
 * @param app vue的app
 */
export function autoImportComponent(app: App) {
  // 全局组件 自动注册
  const views = import.meta.glob('../components/Global/**/**.vue', { eager: true })
  const compts = Object.keys(views).map((key: string) => {
    const pathArr: string[] = key.slice(2).replace('.vue', '').split('/').slice(3).map(item => item[0].toUpperCase() + item.slice(1))
    const comptName = `GlobalCompt${pathArr.join('')}`
    const compt: Component = views[key]
    app.component(comptName, compt.default)
    // console.log('组件自动注册',key, comptName);
    return compt
  })
  return compts
}

/**
 * 自动加载路由，并生成动态路由
 * 路由存储路径为`src/views`
 * 此方法只能在main.ts内调用
 * @returns 返回所有的路由信息
 */
export default function autoImportVueRouter(): Array<VueRouter.RouteRecordRaw> {
  // 动态加载views下的所有文件
  const views = import.meta.glob('@/views/**/**.vue')
  let indexExist = false
  const subRouter: Array<VueRouter.RouteRecordRaw> = Object.keys(views).map((key: string) => {
    const compt = views[key]
    const path = key.toLowerCase().replace(/\.vue$/, '').replace(/.+\/views/g, '')
    useLog().log('自动加载路由=>', key, path)
    if (path === '/index')
      indexExist = true
    return {
      path,
      component: compt,
      meta: {
        sourceCode: key,
      },
    }
  })
  if (!indexExist)
    throw new Error('src/views目录下必须存在Index.vue')
  return subRouter
}
